#include <func.h>
#include <unistd.h>

int main()
{
    //创建客户端的套接字
    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(clientfd, -1, "socket");

    struct sockaddr_in serveraddr;
    memset(&serveraddr, 0, sizeof(serveraddr));
    //指定使用的是IPv4的地址类型 AF_INET
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_port = htons(8080);
    serveraddr.sin_addr.s_addr = inet_addr("192.168.30.129");

    //连接服务器
    int ret = connect(clientfd, (struct sockaddr*)&serveraddr, 
                      sizeof(serveraddr));
    ERROR_CHECK(ret, -1, "connect");
    printf("connect success.\n");

    //进行数据的接收和发送

    fd_set rdset;
    FD_ZERO(&rdset);
    char buff[100] = {0};

    //事件循环
    while(1) {
        FD_SET(STDIN_FILENO, &rdset);
        FD_SET(clientfd, &rdset);
        select(clientfd + 1, &rdset, NULL, NULL, NULL);
        //当select函数返回时，rdset会被修改的

        if(FD_ISSET(STDIN_FILENO, &rdset)) {
            //读取从键盘输入的字符串
            memset(buff, 0, sizeof(buff));
            //通过read函数会把'\n'也读进来
            ret = read(STDIN_FILENO, buff, sizeof(buff));
            if(strcmp(buff, "bye\n") == 0) {
                break;
            }
            //在发送时，不需要发送'\n'
            send(clientfd, buff, ret - 1, 0);
        }

        if(FD_ISSET(clientfd, &rdset)) {
            //从服务器接收数据
            memset(buff, 0, sizeof(buff));
            ret = recv(clientfd, buff, sizeof(buff), 0);
            if(ret == 0) {
                printf("byebye.\n");
                break;
            }
            printf("ret: %d, recv: %s\n", ret, buff);
        }
    }

    close(clientfd);

    return 0;
}
